<template>
  <div class="homeContainer"></div>
</template>

<script setup>
  import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
  import { useRouter } from 'vue-router'
  import html2canvas from 'html2canvas';
  import * as Cesium from 'cesium'
  import icoPoint from '@/assets/home/ico_point.png'

  const router = useRouter()
  let infos = {
    pups: []
  }
  let eventListener = null
  let isShow = true
  let setIntervalID = null

  let mark1Position = Cesium.Cartesian3.fromDegrees(87.38437040774811, 36.80331185906393)
  let mark2Position = Cesium.Cartesian3.fromDegrees(70.59006896173508, 38.12579818590297)
  let mark3Position = Cesium.Cartesian3.fromDegrees(102.91057104834046, 39.957938467697964)
  let pupPosition = null
  let pupPosition2 = null
  let pupPosition3 = null

  let point1 = null
  let point2 = null
  let point3 = null
  let pupData = null
  let pupData2 = null
  let pupData3 = null

  let setIntervalEntity = null

  let viewer = null

  const globeControl = () => {
    viewer = window.cesium?.viewer
    viewer.entities.removeAll()
    // 重置视图位置
    viewer.camera.setView({
      destination: {
        x: 518976.5542229833, // -2523355.235806704,
        y: 7437673.855007478,// 7731150.9445240935,
        z: 3258139.5732106385// 438971.93250270747,
      },
      orientation: {
        heading: 0.020709146240220022, // 0.030142776718315112, // 方向
        pitch: -0.6707780700823931, //-0.6726499441456775, // 视角
        roll: 6.283138705605887, // 6.283066728733684, // 倾斜角度
      },
    })

    setIntervalEntity = viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(87.5398213095874, 61.6649790396606),
      point: {
        color: 'rgba(0, 0, 0, 0)',
        pixelSize: 1
      }
    });

    pupPosition = viewer.scene.globe.ellipsoid.cartesianToCartographic(mark1Position)
    pupPosition2 = viewer.scene.globe.ellipsoid.cartesianToCartographic(mark2Position)
    pupPosition3 = viewer.scene.globe.ellipsoid.cartesianToCartographic(mark3Position)
    
    point1 = viewer.entities.add({
      id: "mark1",
      name: "老商埠",
      position: mark1Position,
      billboard: {
        image: icoPoint,
        width: 58,
        height: 59,
        show: true,
        scale: 1.0,
        disableDepthTestDistance: Number.POSITIVE_INFINITY, // 禁用深度测试
      },
    })
    point2 = viewer.entities.add({
      id: "markdong",
      name: "东城逸家",
      position: mark2Position,
      billboard: {
        image: icoPoint,
        width: 58,
        height: 59,
        show: true,
        scale: 1.0,
        disableDepthTestDistance: Number.POSITIVE_INFINITY, // 禁用深度测试
      },
    })
    point3 = viewer.entities.add({
      id: "markling",
      name: "领秀城",
      position: mark3Position,
      billboard: {
        image: icoPoint,
        width: 58,
        height: 59,
        show: true,
        scale: 1.0,
        disableDepthTestDistance: Number.POSITIVE_INFINITY, // 禁用深度测试
      },
    })

    pupData = {
      id: "point1",
      position: pupPosition,
      title: '老商埠',
      address: '济南市历下区奥体中路玉兰广场3305',
      state: 'on',
      // show: point1.show,
    }
    infos.pups.push(pupData)
    pupData2 = {
      id: "point2",
      position: pupPosition2,
      title: '东城逸家',
      address: '山东省济南市高新区辰祥路',
      state: 'off',
      // show: point2.show,
    }
    infos.pups.push(pupData2)
    pupData3 = {
      id: "point3",
      position: pupPosition3,
      title: '领秀城',
      address: '山东省济南市市中区二环南路2066号',
      state: '',
      // show: point3.show,
    }
    infos.pups.push(pupData3)

    creatPup()
  }
  
  const creatPup = () => {
    let addressimg = new URL("@/assets/home/ico_address.png", import.meta.url)
    let stateimg = new URL("@/assets/home/ico_state.png", import.meta.url)

    infos.pups.forEach(pup => {
      let param = pup
      let mars = document.getElementById(window.cesium.viewer._container.id)
      let tempDiv = document.createElement("div")
      tempDiv.id = param.id
      tempDiv.className = "tempinfo"
      // tempDiv.style.transform = "translate(-170px, -245px)"
      tempDiv.innerHTML = `<div class="temp_box" id="${param.id}_temp_box">
        <div class="temp_title"><div>${param.title}</div></div>
        <div class="temp_address">
          <div class="temp_address_left">
            <img src="${addressimg}" alt="地址">
            <div>地址</div>
          </div>
          <div class="temp_address_right">${param.address}</div>
        </div>
        <div class="temp_address temp_state">
          <div class="temp_address_left">
            <img src="${stateimg}" alt="状态">
            <div>状态</div>
          </div>
          <div class="temp_state_right ${param.state === 'on' ? 'stateOn' : param.state === 'off' ? 'stateOff' : 'stateQuit'} stateOn">${param.state === 'on' ? '运行中' : param.state === 'off' ? '已暂停' : '未运营'}</div>
        </div>
      </div>`
      // stateOff stateQuit
      mars.appendChild(tempDiv)

      let tempbox = document.getElementById(param.id+'_temp_box')
      let img = document.createElement("img") // 创建一个img元素
      img.className = "temp_img"
      img.id = param.id + "_img"
      img.style.width = tempbox.clientWidth
      img.style.height = tempbox.clientHeight

      if(param.state === 'on') {
        img.style.cursor = 'pointer'
        img.className += " temp_img_on"
      }

      html2canvas(tempbox, {
        allowTaint: false,
        useCORS: true,
        width: tempbox.clientWidth,
        height: tempbox.clientHeight,
        backgroundColor: null,
        foreignObjectRendering: false,
        // scale: 2,
        dpi: 300,
      }).then(canvas => {
        img.src = canvas.toDataURL("image/png") // 用canvas的toDataURL导出图片
        tempDiv.appendChild(img)
        tempbox.style.display = 'none'

        nextTick(() => {
          // 标点图片点击事件
          // let tempHandler = document.getElementById('point1_img')
          let tempHandler = document.querySelector('.temp_img_on')
          if(tempHandler) {
            tempHandler.addEventListener('click', () => {
              tempRemoveAll()
            })
          }
        })
      }).catch(err => {
        console.log('err', err);
      })
    })

    setTimeout(() => {
      updateTemp()
    }, 1000)
  }

  // 删除所有标点
  const tempRemoveAll = () => {
    // 删除标记点
    viewer.entities.removeAll() // viewer.entities.removeById(pick.id.id)
    // 删除dom元素
    const cleardom = document.querySelectorAll(".tempinfo")
    Array.from(cleardom).forEach(item => {
      item.remove()
    })
    isShow = false
    router.push("/basePage")
  }
  
  // 更新标点位置
  const updateTemp = () => {
    infos.pups.forEach(pup => {
      // 转为弧度wgs84坐标
      let woredcoodinates = Cesium.Cartesian3.fromRadians(pup.position.longitude, pup.position.latitude, pup.position.height)
      if(isShow) {
        // 一直更新标签位置
        viewer.scene.postRender.addEventListener(() => {
          // wgs84坐标转为屏幕坐标
          let screenpos = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, woredcoodinates)
          let temp = document.getElementById(pup.id)
          if (temp) {
            setTimeout(() => {
              temp.style.top = screenpos?.y - 245 + "px"
              temp.style.left = screenpos?.x - 180 + "px"
            }, 0)
          }
        })
      }
    })
    
    let initialHeading = 2.283766536212693;
    // 步长
    let step = 0.05;
    if(setIntervalID) {
      clearInterval(setIntervalID)
    }
    setIntervalID = setInterval(() => {
      if (initialHeading > 363) {
        initialHeading = 2.283766536212693;
      }
      var offset = new Cesium.HeadingPitchRange(
        Cesium.Math.toRadians(initialHeading),
        -Cesium.Math.toRadians(0.5),
        5000000
      );
      viewer.zoomTo(setIntervalEntity, offset);
      initialHeading += step;

      point1.show = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, viewer.camera.position).isPointVisible(mark1Position)
      point2.show = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, viewer.camera.position).isPointVisible(mark2Position)
      point3.show = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, viewer.camera.position).isPointVisible(mark3Position)

      if(document.getElementById(pupData.id + "_img")) {
        document.getElementById(pupData.id + "_img").style.display = point1.show ? "block" : "none"
      }
      if(document.getElementById(pupData2.id + "_img")) {
        document.getElementById(pupData2.id + "_img").style.display = point2.show ? "block" : "none"
      }
      if(document.getElementById(pupData3.id + "_img")) {
        document.getElementById(pupData3.id + "_img").style.display = point3.show ? "block" : "none"
      }
    }, step * 2000);
  }

  onMounted(() => {
    globeControl()
  })

  onBeforeUnmount(() => {
    if(setIntervalID) {
      clearInterval(setIntervalID)
    }
    if(viewer) {
      viewer.entities.removeAll()
    }
  })
</script>

<style lang="scss" scoped>
  
</style>
